<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { createWebSocket } from './utils/websocket'
import type { WSStatus } from './utils/websocket'
import { WS_URL } from './utils/config'
import { loginUserDate } from './mock'

defineOptions({ name: 'RealTimeView' })

// 定义按钮配置接口
interface ButtonConfig {
  label: string
  value:
    | 'ma_open_rtsp'
    | 'ma_stop_rtsp'
    | 'voice'
    | 'ma_push_take_photo'
    | 'screen'
  type: 'open' | 'close'
}

// 按钮列表
const btnList = ref<ButtonConfig[]>([
  { label: '开启画面', value: 'ma_open_rtsp', type: 'open' },
  { label: '关闭画面', value: 'ma_stop_rtsp', type: 'close' },
  { label: '截屏', value: 'ma_push_take_photo', type: 'open' },
  { label: '全屏', value: 'screen', type: 'open' },
])

const content = ref<string>('登录用户信息')
const wsStatus = ref<WSStatus>('disconnected')
const ws = ref<any>(null)

// 初始化WebSocket连接
const initWebSocket = () => {
  ws.value = createWebSocket({
    url: WS_URL,
    onConnect: () => {
      wsStatus.value = 'connected'
      console.log('WebSocket连接已建立')
      // 管理员登录
      ws.value.send(loginUserDate)
    },
    onMessage: (message: any) => {
      handleWebSocketMessage(message)
    },
    onDisconnect: () => {
      wsStatus.value = 'disconnected'
      console.log('WebSocket连接已关闭')
    },
    onError: error => {
      wsStatus.value = 'disconnected'
      console.error('WebSocket连接错误:', error)
    },
  })

  // 开始连接
  ws.value.connect()
}

const admin_info = ref<any>({}) // 管理员数据
const active_devices = ref<any[]>([]) // 活跃设备列表
// 处理接收到的WebSocket消息
const handleWebSocketMessage = (message: any) => {
  // 根据消息类型处理不同的业务逻辑
  switch (message.cmd) {
    case 'ma_login':
      admin_info.value = message.admin_info
      // 连接成功后获取实时、状态等心跳包
      ws.value.send({
        act: 'ma_get_active_devices',
      })
      break
    case 'ma_get_active_devices':
      active_devices.value = message.data
      content.value = message.data
      break
  }
}

const player = ref<any>(null)
const videoElement = ref<any>(null)

// 操作硬件
const handleClick = (val: ButtonConfig['value']) => {
  switch (val) {
    case 'ma_open_rtsp':
      ws.value?.send({
        act: val,
        device_id: active_devices.value[0].user_info.device_id,
      })
      // 监听实时监控事件
      ws.value?.on(val, (message: any) => {
        console.log()
        player.value = new (window as any).ZLMRTCClient.Endpoint({
          // element: document.getElementById('remoteVideo'), // video 标签
          element: videoElement.value, // video 标签
          debug: true, // 是否打印日志
          zlmsdpUrl: message.webrtc_url, //流地址
          simulcast: true,
          useCamera: true,
          audioEnable: true,
          videoEnable: true,
          recvOnly: true,
          resolution: {
            w: 1280,
            h: 720,
          },
        })
      })
      break
    case 'ma_stop_rtsp':
      player.value?.close()
      player.value = null
      // TODO 当有多个设备时，需要根据业务需求操作。
      // 发送WebSocket消息
      ws.value?.send({
        act: val,
        user_id: active_devices.value[0].user_info.user_id,
      })
      ws.value?.on(val, () => {
        console.log('截屏成功')
      })
      break
    case 'ma_push_take_photo':
      // 发送WebSocket消息
      ws.value?.send({
        act: val,
        user_id: active_devices.value[0].user_info.user_id,
      })
      ws.value?.on(val, () => {
        console.log('截屏成功')
      })
      break
  }
}

// 组件挂载时初始化WebSocket
onMounted(() => {
  initWebSocket()
})

// 组件卸载时清理WebSocket
onUnmounted(() => {
  // 关闭视频播放器
  if (player.value) {
    player.value.close()
    player.value = null
  }
  // 关闭WebSocket连接
  if (ws.value) {
    ws.value.close()
  }
  // 清理其他资源
  active_devices.value = []
  admin_info.value = {}
})
</script>

<template>
  <div class="btn-box">
    <el-button
      v-for="item in btnList"
      :key="item.value"
      type="primary"
      @click="handleClick(item.value)"
    >
      {{ item.label }}
    </el-button>
    <el-button
      :type="
        wsStatus === 'connected'
          ? 'success'
          : wsStatus === 'connecting'
            ? 'warning'
            : 'danger'
      "
      disabled
      style="margin-left: 20px"
    >
      {{
        {
          disconnected: '未连接',
          connecting: '连接中...',
          connected: '已连接',
        }[wsStatus]
      }}
    </el-button>
  </div>
  <div class="content-box">
    <div class="info-box">
      <pre>{{ content }}</pre>
    </div>
    <div class="video-box">
      <video
        autoplay
        controls
        ref="videoElement"
        style="width: 100%; height: 100%"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.btn-box {
  display: flex;
  background-color: #f5f5f5;
  padding: 20px;
  align-items: center;
}

.content-box {
  display: flex;
  flex: 1;
  margin-top: 10px;
  padding: 10px;
  border: 1px solid #ccc;
  overflow: hidden;
  .info-box {
    width: 300px;
    min-width: 300px;
    height: 100%;
    padding: 10px;
    margin-right: 10px;
    overflow: auto;
  }
}

:deep(.el-button + .el-button) {
  margin-left: 10px;
}

.video-box {
  flex: 1;
  height: 100%;
}
</style>
